package br.com.controler;

import br.com.modelo.DavCabecalho;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import util.JPAUtil;
import util.Utilitario;

/**
 *
 * @author Administrador
 */
public class DavCabecalhoControler {

    public static String retornaNumeroDav() {
        EntityManager em = JPAUtil.retornarFabrica().createEntityManager();
        Query q = em.createQuery("SELECT MAX(d.numeroDav) FROM DavCabecalho d");
        String list = (String) q.getSingleResult();
        em.close();
        if (list == null) {
            list = "0";
        }
        Integer qtd = (Integer.parseInt(list) + 1);
        String retorno = Utilitario.repete("0", (10 - (qtd.toString().length()))) + (Integer.parseInt(list) + 1);
        return retorno;
    }

    public static List<DavCabecalho> retornaDavEmAberto() {
        EntityManager em = JPAUtil.retornarFabrica().createEntityManager();
        Query q = em.createQuery("FROM DavCabecalho d WHERE d.situacao = 'P'");
        List<DavCabecalho> list = q.getResultList();
        em.close();
        return list;
    }

    public static DavCabecalho retornaDavPorId(Integer idDAV) {
        EntityManager em = JPAUtil.retornarFabrica().createEntityManager();
        Query q = em.createQuery("FROM DavCabecalho d WHERE d.id = ?");
        q.setParameter(1, idDAV);
        DavCabecalho retorno;
        try {
            retorno = (DavCabecalho) q.getSingleResult();
            em.close();
            return retorno;
        } catch (javax.persistence.NoResultException e) {
            em.close();
            return null;
        }
    }
}
